<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>360汇云客服系统</title>
    <link rel="stylesheet" href="../../js/libs/layui/css/layui.css" media="all">
    <style type="text/css">
        .layui-layer.layui-layim-chat {
            position: initial !important;
            box-shadow: none;
        }

        .layim-chat-send .layim-menu-box {
            top: -80px !important;
        }

        .layui-unselect.layim-chat-list {
            display: block !important;
        }

        .layim-chat-box {
            margin-left: 200px !important;
        }

        .layim-chat-main {
            width: auto !important;
            left: 200px !important;
        }

        .layim-chat-footer {
            left: 200px !important;
            bottom: 100px !important;
        }

        .layim-chat-textarea {
            height: 140px;
        }

        .layim-chat-textarea textarea {
            height: 140px;
        }

        .layim-chat-bottom {
            border-top: 1px solid #F1F1F1
        }

        .layui-badge {
            font-size: 12px !important;
            border-radius: 12px;
        }

        /**设置左侧栏颜色*/
        .layim-chat-list {
            background-color: #f7f3f3 !important;
        }

        .layim-chat-list li {
            background-color: #f0f0f0;
        }

        .layim-chat-list li.layim-this {
            background-color: #e6e6e6 !important;
        }

        .layui-layer-loading .layui-layer-content {
            padding-left: 40px;
            line-height: 32px;
            width: 200px !important;
        }

    </style>
</head>
<body class="layui-layout-body theme-purple" style="height: 100vh">
<div class="layadmin-tabspage-none">
    <div id="chatTips" style="text-align: center;width: 100%;display: none">
        <div style="width: 200px;height: 200px;margin:150px auto 0 auto;">
            <img src="../../images/public/im/no_his.png" style="width: 100px;height: 100px"/>
            <div class="text" style="margin-top: 20px"></div>
        </div>
    </div>

</div>

<script src="../../js/libs/layui/layui.js"></script>
<script>
    var $;
    layui
        .config({
            base: 'module/',
            version: '@current.time@'
        }).extend({
        env: "{/}/imcs/module/public/env",
        setter: "{/}/imcs/module/public/setter",
        tools: "{/}/imcs/module/public/tools",
        crypto: '{/}/imcs/module/public/utils/crypto',
    })
        .use(["layim", 'setter', 'tools'], function () {
            var layim = layui.layim;
            $ = layui.jquery;
            var config = layui.setter;
            var width = $('.layui-layout-body').width() - 5 + "px";
            var height = $('.layui-layout-body').height() + "px";
            let tools = layui.tools;
            var userInfo = config.getUser()['userInfo'];
            var defaultUserAvatar = '../../images/public/im/user.gif';//默认用户头像
            var defaultCsAvatar = '../../images/public/im/kf.png';//默认客服头像
            var thisSession = {};//当前会话
            var sessionList = [];//会话列表
            var $chatTips = $("#chatTips");//信息dom
            var TYPE = "im";
            var  imInit=false;


            var chat_params = {
                area: [width, height],
                maxmin: false,
                move: false,
                offset: ['50px', '0']
                , full: false
                , resizing: false
                // , restore: false
                , min: false
                , end: false
            }

            methods = {
                //入口
                //如果im登陆失败 展示错误信息
                //1，初始化im配置
                // 如果登录成功
                //2,如果有session 创建列表
                init() {
                    methods.hideErrMsg();
                    var csLoginStatus = tools.getAndDelTempData("ws_status_"+TYPE);
                    if (null == csLoginStatus || !userInfo) {
                        //如果不存在 则忽略
                        return
                    }
                    //初始化配置
                    methods.init_im_config();

                    if (csLoginStatus.state != true && csLoginStatus.state != 1) {
                        //展示 cs登录错误
                        methods.showErrMsg(csLoginStatus.msg || '')
                    } else {
                        //获取session
                        methods.parseList(true)
                    }
                },
                //初始化im配置
                init_im_config() {
                    if(imInit){return}
                    layim.config({
                        init: {
                            //配置客户信息
                            mine: {
                                "username": userInfo.username //我的昵称
                                , "id": userInfo.userId //我的ID
                                , "status": "online" //在线状态 online：在线、hide：隐身
                                , "remark": userInfo.remark || '' //我的签名
                                , "avatar": userInfo.avatar ? userInfo.avatar : defaultCsAvatar //我的头像 默认客服头像
                            }
                        }
                        //开启客服模式
                        , brief: true
                        //更多历史
                        , chatLog: function ($em) {
                            thisSession.em = $em;
                            var pg = 1;
                            for (var i in sessionList) {
                                if (sessionList[i].userId == thisSession.userId) {
                                    pg = sessionList[i].pageNum || 1;
                                    break;
                                }
                            }
                            //发送查询历史记录
                            parent.sendMessage(TYPE, {
                                cmd: 19,
                                userId: userInfo.userId,
                                fromUserId: thisSession.userId,
                                offset: pg,
                                type: 1,
                                chatType: 3//客服
                            })
                        }
                    });
                    methods.events();
                    imInit=true;
                },

                /**
                 * 生成会话列表
                 * 加载本地会话列表
                 * */
                parseList(first) {
                    //获取session
                    sessionList = tools.getTempData("im_session_data_" + TYPE);
                    if (!sessionList || sessionList == {}) {
                        //展示 无会话连接信息
                        methods.showErrMsg("没有会话接入");
                        return
                    }
                    methods.hideErrMsg();
                    //创建列表
                    for (var i in sessionList) {
                        var session = sessionList[i];
                        var active = false;
                        if (first && (!thisSession) || !thisSession.userId) {
                            active = true;
                            thisSession = session;
                        }
                        session.active = active;
                        session.show = true;
                        session.isBefore = !first;
                        methods.createChat(session);
                    }
                    if (first) {
                        $(".layui-unselect.layim-chat-list").height(height)
                    }
                    //加载本地消息
                    methods.getLocalMessage();

                    //无数据 没有会话
                    if ($(".layui-layer.layui-layim-chat").length == 0) {
                        methods.showErrMsg("当前没有会话接入")
                    }

                },
                /**
                 * 创建会话 单个 chat
                 * session
                 * first 是否第一次
                 * */
                createChat(session) {
                    layim.embchat($.extend({}, chat_params, {
                        name: session.userNick,
                        type: 'kefu',
                        active: session.active,//是否选中
                        show: session.show,
                        avatar: session.userAvatar || defaultUserAvatar,
                        id: session.userId,
                        sessionId: session.sessionId,
                        isBefore: session.isBefore,
                        csId: session.csId
                    }))
                    //是否携带有聊天记录
                    if (session.data && session.data.length > 0) {
                        //session 带有消息
                        for (var j in session.data) {
                            var chatData = session.data[j];
                            if (typeof (chatData) == 'string') {
                                chatData = JSON.parse(chatData);
                            }
                            var msg = {
                                username: session.userNick,
                                avatar: session.userAvatar || defaultUserAvatar,
                                id: session.userId,
                                type: "kefu", //聊天窗口来源类型，从发送消息传递的to里面获取,
                                content: chatData.content,
                                mine: false, //是否我发送的消息，如果为true，则会显示在右方,
                                timestamp: parseInt(chatData.createTime)
                                , isRead: chatData.isRead || 0
                                , msgId: chatData.id
                                , chatType: chatData.chatType//消息类型,
                            }
                            layim.getMessage(msg);
                        }


                    }

                },
                //加载本地消息
                getLocalMessage() {
                    var messageDataList = tools.getTempData("im_message_data_" + TYPE);
                    if (messageDataList) {
                        for (var i in messageDataList) {
                            methods.chatMessage(messageDataList[i])
                        }
                    }
                },
                //layim事件监听
                events() {
                    //聊天切换
                    layim.on("chatChange", function (res, index) {
                        thisSession = null;
                        for (var i in sessionList) {
                            if (sessionList[i].userId == res.data.id) {
                                thisSession = sessionList[i]
                            }
                        }
                        //如果没有sessionid
                        if (!thisSession || !thisSession.sessionId) {
                            return
                        }
                        //已读
                        var unReadNum = res.listElem.find(".layui-badge").html();
                        if (!unReadNum && unReadNum == "0") {
                            return
                        }
                        parent.readMsg(TYPE, res.data.id, unReadNum);
                        res.listElem.find(".layui-badge").html("0").hide();

                    })
                    //查看更多记录
                    layim.on('chatlog', function (data, ul) {
                    })
                    //返回按钮
                    layim.on('back', function (data, ul) {

                    })
                    //监听发送消息
                    layim.on("sendMessage", function (res) {
                        var mine = res.mine; //包含我发送的消息及我的信息
                        var to = res.to; //对方的信息
                        var msg = {
                            "from": userInfo.userId,
                            "to": thisSession && thisSession.userId == to.id ? thisSession.sessionId : to.sessionId,
                            "cmd": 11,
                            "createTime": new Date().getTime(),
                            "msgType": res.msgType || 0,
                            "chatType": 3,//客服聊天模式
                            "groupId": res.groupId || '',
                            "content": mine.content
                        }
                        //调用parent 发送
                        parent.sendMessage(TYPE, msg);
                    })
                },
                /**
                 * 处理消息 单聊
                 * */
                chatMessage(data) {
                    if (!data) {
                        return
                    }
                    if ($.isArray(data)) {
                        //如果是一个数组
                        for (var i in data) {
                            methods.parseMsg(data[i])
                        }
                    } else {
                        methods.parseMsg(data)
                    }
                },
                /**
                 * 构成聊天消息 一次一条
                 */
                parseMsg(msgData) {
                    if (!msgData.from && msgData.command) {
                        msgData = msgData.data;
                    }
                    var isRead = msgData.isRead;
                    if (thisSession && thisSession.id == msgData.from) {
                        isRead = true;//如果当前正在和他聊
                    }
                    //聊天
                    var msg = {
                        username: msgData.fromNickName || msgData.formName,
                        avatar: msgData.avatar || defaultUserAvatar,
                        id: msgData.from,
                        type: "kefu", //聊天窗口来源类型，从发送消息传递的to里面获取,
                        content: msgData.content,
                        mine: false, //是否我发送的消息，如果为true，则会显示在右方,
                        timestamp: parseInt(msgData.createTime)
                        , isRead: isRead
                        , msgId: msgData.id
                        , chatType: msgData.chatType//消息类型,
                    }
                    layim.getMessage(msg);
                    if (isRead) {
                        //触发阅读
                        parent.readMsg(TYPE, msgData.from);
                    }
                },
                parseHistoryMsg(msgData) {
                    var msgList = [];
                    if (msgData && msgData.length > 0 && thisSession) {
                        for (var i in msgData) {
                            var chatMsg = msgData[i];
                            var isMe = chatMsg.fromUserId == thisSession.userId ? false : true;
                            var msg = {
                                username: isMe ? userInfo.nick : thisSession.nick,
                                avatar: chatMsg.avatar || defaultUserAvatar,
                                id: isMe ? chatMsg.toUserId : chatMsg.fromUserId,
                                type: "kefu", //聊天窗口来源类型，从发送消息传递的to里面获取,
                                content: chatMsg.content,
                                mine: isMe, //是否我发送的消息，如果为true，则会显示在右方,
                                timestamp: parseInt(chatMsg.createTime),
                            }
                            msgList.push(msg);
                        }
                    }
                    layim.addHistory(msgList.length > 0, msgList, thisSession.em);
                    if (msgList.length > 0) {

                        for (var i in sessionList) {//增加页码
                            if (sessionList[i].userId == thisSession.userId) {
                                var pg = sessionList[i].pageNum || 1;
                                sessionList[i].pageNum = pg + 1;
                                break;
                            }
                        }
                    }
                },
                /**
                 * 处理会话变动
                 * @param session 一条
                 * @param changeType
                 */
                sessionChange(session, changeType) {
                    methods.hideErrMsg()
                    var active = false, show = false;
                    var $chat = $(".layui-layim-chat");
                    if ($chat.length == 0 || $chat.find("li:visible").length == 0) {
                        active = show = true;
                    } else if (changeType == 4) {//离线消息
                        show = true;
                    }
                    //判断当前 sessionList 是否含有
                    var has = false;
                    if (sessionList && sessionList != {}) {
                        for (var i in sessionList) {
                            if (i == session.userId) {
                                has = true;
                                sessionList[i] = session;//覆盖赋值
                                break;
                            }
                        }
                    }

                    if (thisSession && thisSession.userId == session.userId) {
                        thisSession = session;
                    }
                    if (!has) {
                        sessionList[session.userId] = session;
                        session.active = active;
                        session.show = true;
                        session.isBefore = false;
                        methods.createChat(session);
                    }
                },
                showErrMsg(msg) {
                    $chatTips.find(".text").html(msg);
                    $chatTips.show();
                    layer.closeAll()
                },
                hideErrMsg() {
                    $chatTips.find(".text").html("");
                    $chatTips.hide();
                }
            }
            methods.init();
        });

    //注册页面级方法 供其他页面调用
    /**
     *新消息 聊天
     */
    function chat(msgData) {
        if (msgData) {
            methods.chatMessage(msgData)
        }
    }

    /**
     * 会话变动
     * sessionData  {changeType:1,data:[]||{}} 形式
     * changeType  变动类型 对应 socket 34的类型
     */
    function sessionChange(sessionData) {
        if (sessionData != null && sessionData.changeType != null && sessionData.data != null) {
            if ($.isArray(sessionData.data)) {
                for (var i in sessionData) {
                    methods.sessionChange(sessionData.data[i], sessionData.changeType)
                }
            } else {
                methods.sessionChange(sessionData.data, sessionData.changeType)
            }
        }
    }

    /**
     *加载历史记录 聊天记录
     */
    function historyMessage(msgData) {

        methods.parseHistoryMsg(msgData)
    }

    /**
     * 会话变动通知
     */
    function  stateChange() {
         methods.init();
    }

</script>
</body>
</html>